#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cbm.h>
#include <errno.h>

#include "Buffers.h"
#include "Trim.h"
#include "Splitter.h"
#include "Drives.h"

#pragma code-name("RENCODE");
#pragma rodata-name("RENCODE");

void renameUsage()
{
	printf("\nusage: ren :existingfile :newfile\n");
}

unsigned char renameFile(unsigned char driveIndex)
{
	unsigned char r = 0, i = 0;
	int result = 0;
	drive_t *drive = &drives[driveIndex];
	tokenCollection_t *collection = NULL;
	static char buffer[256];
	parsedPath_t *spath = NULL;
	parsedPath_t *tpath = NULL;

	strcpy(buffer, buffer3);

	collection = splitString(buffer);

	if(collection->count != 3)
	{
		renameUsage();
		free(collection);
		return 0;
	}

	spath = parsePath(1, collection, driveIndex);
	tpath = parsePath(2, collection, driveIndex);

	if(getDrive(spath->device) == 0xFF)
	{
		printf("\nUnknown source device.");
		free(collection);
		free(spath);
		free(tpath);
		return 1;
	}

	if(getDrive(tpath->device) == 0xFF)
	{
		printf("\nUnknown target device.");
		free(collection);
		free(spath);
		free(tpath);
		return 1;
	}

	if(strcmp(spath->file, tpath->file) == 0)
	{
		printf("\nSource and target file names must be\ndifferent.");
		free(collection);
		free(spath);
		free(tpath);
		return 1;
	}

	if(isPattern(spath->file) || isPattern(tpath->file))
	{
		printf("\nSource and target files must not be\npatterns.");
		free(collection);
		free(spath);
		free(tpath);
		return 1;
	}

	if(strcmp(spath->path, tpath->path) != 0 || 
		spath->device != tpath->device ||
		spath->drive != tpath->drive)
	{
		printf("\nCannot rename file to another path.\nPlease use the MOVE command.");
		free(collection);
		free(spath);
		free(tpath);
		return 1;
	}

	memset(buffer1, 0, sizeof(buffer1));
	//removeQuotes(1, collection);
	//removeQuotes(2, collection);
	sprintf(buffer1, "r%1u:%s=%s", spath->drive, tpath->file, spath->file);

	r = cbm_open(15, spath->device, 15, buffer1);
	memset(buffer2, 0, sizeof(buffer2));
	result = cbm_read(15, buffer2, sizeof(buffer2));
	cbm_close(15);

	if(buffer2[0] == '0' && buffer2[1] == '0') 
	{
		free(collection);
		free(spath);
		free(tpath);
		return 0;
	}

	printf("\n%s", buffer2);
	free(collection);
	free(spath);
	free(tpath);
	return _oserror;
}
